package com.windy.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.windy.app.entity.Product;
import com.windy.app.vo.Result;
import com.windy.mapper.ProductMapper;
import com.windy.service.IProductService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("productService")
@GlobalTransactional
public class ProductServiceImpl extends ServiceImpl<ProductMapper,Product> implements IProductService {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Value("${topic}")
    private String TOPIC;
    @Value("${tag}")
    private String TAG;

    @Override
    public Product findById(Long id) {
        return this.baseMapper.selectById(id);
    }

    @Override
    public List<Product> findAllProduct() {
        return this.baseMapper.selectByMap(new HashMap<String,Object>());
    }

    @Override
    public Result auditProduct(Long id) {
        Product product = this.baseMapper.selectById(id);
        if (product == null){
            return new Result(false,"商品"+id+"不存在");
        }
        product.setId(id);
        int i = this.baseMapper.updateById(product);

        //发送同步索引库消息
        SendResult sendResult = rocketMQTemplate.syncSend(TOPIC + ":" + TAG, product);
        if (sendResult.getSendStatus() == SendStatus.SEND_OK){
            return new Result(true,"同步商品成功");
        }else {
            //TODO：哪个消息 什么时间 发送状态【补偿】
            return new Result(false,"同步商品失败");
        }
    }

    @Override
    public Result<Product> delStore(Long id, Integer number) {
        Product product = this.baseMapper.selectById(id);
        if (product == null){
            return new Result(false,"商品"+id+"不存在");
        }
        product.setId(id);
        product.setStore(product.getStore()-number);
        int i = this.baseMapper.updateById(product);
        return new Result<Product>(true,"删除库存成功",product);
    }
}
